import Flutter
import UIKit
import PayPalCheckout
import os

public class SwiftPaypalFlutterPlugin: NSObject, FlutterPlugin {
    
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "paypal_flutter", binaryMessenger: registrar.messenger())
        let instance = SwiftPaypalFlutterPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        case "setup":
            guard let arguments = call.arguments as? [String : Any],
                  let clientID = arguments["clientID"] as? String,
                  let returnUrl = arguments["returnUrl"] as? String,
                  let environment = arguments["environment"] as? Int else { return }
            NSLog("\(clientID) \(returnUrl) \(environment)")
            setupConfig(result: result, clientID: clientID, returnUrl: returnUrl, environment: environment)
        case "pay":
            guard let arguments = call.arguments as? [String : Any],
                  let total = arguments["total"] as? String else { return }
            NSLog("\(total)")
            pay(result: result, total: total)
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    func setupConfig(result: FlutterResult, clientID: String, returnUrl: String, environment: Int) {
        let config = CheckoutConfig(
            clientID: clientID,
            returnUrl: returnUrl,
            environment: Environment(rawValue: environment)!)
        config.currencyCode = CurrencyCode.eur
        config.userAction = UserAction.payNow
        Checkout.set(config: config)
        result("OK")
    }
    
    func pay(result: @escaping FlutterResult, total: String) {
        Checkout.start(
            createOrder: { createOrderActions in
                let amount = PurchaseUnit.Amount(currencyCode: .eur, value: total)
                let purchaseUnit = PurchaseUnit(amount: amount)
                let appContext = OrderApplicationContext(userAction: .payNow)
                let order = OrderRequest(
                    intent: .capture,
                    purchaseUnits: [purchaseUnit],
                    applicationContext: appContext)
                createOrderActions.create(order: order)
            }, onApprove: { approval in
                approval.actions.capture { success, error in
                    if let error = error {
                        NSLog("CaptureOrderResult: \(error.localizedDescription)")
                        result(error.localizedDescription)
                    } else {
                        NSLog("CaptureOrderResult: \(success?.description ?? "")")
                        result(success)
                        // CaptureOrderResult
                        // if let resp = success as? PPCCaptureActionSuccess{
                        //     result(resp)
                        // }else{
                        //     result("SUCCESS")
                        // }
                        
                    }
                }
            }, onCancel: {
                NSLog("Buyer canceled the PayPal experience.")
                result("CANCEL")
            }, onError: { errorInfo in
                NSLog("Error: \(errorInfo)")
                result(errorInfo.reason)
            }
        )
    }
}
